import { getToken, setToken, removeToken,setTimeStamp } from '@/utils/auth'
import {login,getInfo,getAvar} from "@/api/user"
import {resetRouter} from "@/router"
export default  {
  namespaced: true,
  state: {
    token:getToken()||null,
    userinfo:{},
  },
  mutations: {
    // 设置token
    setToken(state,token){
      setToken(token);
      state.token = getToken();
      setTimeStamp();
    },

    // 删除token
    removeToken(state){
      removeToken();
      state.token = null;
    },
    GETUSERINFO(state,data){
      state.userinfo = data;
    },
     LOGOUT(state){
        removeToken();
        state.token = null;
        state.userinfo = {};
    },
    removeUserInfo(state){
      state.userinfo = {};
    }

  },
  actions: {
    async Login(context,data){
      // console.log("AAA",data);
      let result =  await login(data);
      context.commit("setToken",result);
    },
    async getUserInfo(context){
      let result = await getInfo();
      console.log(result,"userINfo");
      let result1 = await getAvar(result.userId);
      console.log("2",result1);
      const data = {...result,...result1}
      context.commit("GETUSERINFO",data);
      return data;
    },
    logout(context){
      context.commit("LOGOUT");
      // 1.重置路由
      resetRouter();
      //2.还要清空state中的数据.
      // root：true表明此时是父模块，而不是子模块。
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}